<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <!-- <el-button type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button> -->
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <DetailDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { ExportObj, KeyEvent } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import DetailDrawer from "./detailDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, View } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useDateFormat } from "@vueuse/core";
// import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ExportColType } from "@/enums/sysEnum";
import { dateRender, enumRender, orgRender, userRender } from "@/hooks/useColumnRender";
import { useDataStore } from "@/stores/modules/data";

const initVar = reactive({
  tbName: "key_event",
  tbCnName: "关键事件"
});

const defaultDate = ref<Date>(new Date());

// ProTable 实例
const proTable = ref<ProTableInstance>();
// const { BUTTONS } = useAuthButtons();
const dataStore = useDataStore();

const initParam = reactive({
  condition: {},
  options: { sort: { occ_time: -1 } }
});

const orgList = computed(() => dataStore.orgList);
const userList = computed(() => dataStore.userList);
const customerList = computed(() => dataStore.getEnumByCsName("customer_classify"));
onMounted(() => {
  dataStore.findProductList();
  dataStore.findOrgList();
  dataStore.findEnumByCsName("customer_classify");
  dataStore.findUserList();
});

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  if (newParams.condition && newParams.condition.occ_time) {
    let curDate = new Date(newParams.condition.occ_time);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.occ_time = { $gte: startDate, $lte: endDate };
  }
  return apiService.findPage(initVar.tbName, newParams.condition, newParams.options);
};

// 表格配置项
const columns = reactive<ColumnProps<KeyEvent>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "name", label: "标题", search: { el: "input", like: true, order: 1 } },
  {
    prop: "type",
    label: "类别",
    width: 120,
    // 字典请求携带参数
    enum: () => apiService.findClassify("KEY_EVENT_TYPE"),
    fieldNames: { label: "name", value: "_id" },
    search: { el: "select", props: { filterable: true }, order: 2 }
  },
  {
    prop: "occ_time",
    label: "发生时间",
    width: 140,
    render: dateRender,
    search: { el: "date-picker", props: { type: "month" }, order: 3, defaultValue: defaultDate, label: "月份" }
  },
  { prop: "customer", label: "客户", width: 140, render: scope => enumRender(scope, customerList) },
  { prop: "duty_orgId", label: "负责组", width: 140, render: scope => orgRender(scope, orgList) },
  { prop: "duty_userId", label: "负责人", width: 100, render: scope => userRender(scope, userList) },
  { prop: "createUser", label: "录入用户", width: 100, render: scope => userRender(scope, userList) },
  { prop: "createDate", label: "录入时间", width: 140, render: dateRender },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 240 }
]);

// 删除信息
const deleteAccount = async (params: KeyEvent) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除【${params.name}】`);
  proTable.value?.getTableList();
};

const getExcelConfig = (): ExportObj => {
  let newParams = JSON.parse(JSON.stringify(proTable.value?.totalParam));
  if (newParams.condition.occ_time) {
    let curDate = new Date(newParams.condition.occ_time);
    let [year, month] = [curDate.getFullYear(), curDate.getMonth()];
    let startDate = new Date(year, month, 1);
    let endDate = new Date(year, month + 1, 0, 23, 59, 59);
    newParams.condition.occ_time = { $gte: startDate, $lte: endDate };
  }
  return {
    params: newParams,
    tableName: initVar.tbName,
    enumTypes: ["KEY_EVENT_TYPE", "customer_classify"],
    tableConfigs: [
      { tableName: "users", fields: ["_id", "userName"] },
      { tableName: "orgs", fields: ["_id", "name"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "事件标题", width: 40, ext: { prop: "name", type: ExportColType.DEFAULT } },
      { header: "发生时间", width: 10, ext: { prop: "occ_time", type: ExportColType.DATE } },
      {
        header: "事件类别",
        width: 10,
        ext: { prop: "type", type: ExportColType.ENUM, key: "KEY_EVENT_TYPE", label: "name", value: "_id" }
      },
      {
        header: "客户",
        width: 10,
        ext: { prop: "customer", type: ExportColType.ENUM, key: "customer_classify", label: "name", value: "_id" }
      },
      { header: "负责组", width: 18, ext: { prop: "duty_orgId", type: ExportColType.TABLE, key: "orgs" } },
      {
        header: "负责人",
        width: 10,
        ext: { prop: "duty_userId", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "事件内容", width: 40, ext: { prop: "summary", type: ExportColType.DEFAULT } },
      {
        header: "创建人",
        width: 10,
        ext: { prop: "createUser", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 12, ext: { prop: "createDate", type: ExportColType.DATE } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(
      apiService.commonExport,
      `关键事件清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`,
      "",
      getExcelConfig(),
      false
    )
  );
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof DetailDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<KeyEvent> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
